<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" :model="queryForm" class="query-form">
        <el-form-item label="部门名称">
          <el-input v-model.trim="keywords" style="width: 180px" clearable placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="请选择状态" style="width: 180px" clearable>
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button type="primary" v-if="!userInfo?.roleArr?.includes('root')"
            @click="handleAdd(userInfo?.deptId || 0)">新增部门</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="filterLists" row-key="id" border stripe default-expand-all style="width: 100%">
        <el-table-column prop="name" label="部门名称" min-width="300" show-overflow-tooltip />
        <el-table-column prop="code" label="部门编码" min-width="100" show-overflow-tooltip />
        <el-table-column prop="remark" label="部门描述" min-width="160" show-overflow-tooltip />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status == 1 ? 'success' : 'danger'">
              {{ scope.row.status == 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ $formatTimestamp(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            <el-button size="small" type="primary" @click="handleAdd(scope.row.id)">新增子部门</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 部门表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form ref="formRef" :model="deptForm" :rules="deptRules" label-width="80px">
        <el-form-item label="上级部门" prop="pid" v-if="deptForm.pid != 0">
          <el-tree-select v-model="deptForm.pid" :data="list"
            :props="{ value: 'id', label: 'name', children: 'children' }" node-key="id" placeholder="请选择上级部门"
            check-strictly default-expand-all style="width: 100%" />
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model.trim="deptForm.name" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model.trim="deptForm.code" placeholder="请输入部门编码" />
        </el-form-item>
        <el-form-item label="部门描述" prop="remark">
          <el-input v-model.trim="deptForm.remark" placeholder="请输入部门描述" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="deptForm.sort" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="deptForm.status" placeholder="请选择状态">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useUser } from '@/store/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  apiDeptList,
  apiDeptAdd,
  apiDeptUpdate,
  apiDeptDelete,
} from '@/api/system/dept'
import { apiGetModuleInfo } from '@/api/system/module'

const route = useRoute()
const moduleInfo = ref<Record<string, any>>({})
const { userInfo } = useUser()

// 查询表单
const queryForm = ref<Record<string, any>>({})
const keywords = ref('')

// 列表与分页
const list = ref<[]>([])

// 过滤条件
const condition = (node: any) => {
  return node.name.includes(keywords.value)
}

// 过滤列表
const filterLists = computed(() => {
  if (!keywords.value) return list.value
  return list.value
    .map((node) => filterTree(node, condition))
    .filter((node) => node !== null)
})

// 获取列表
const fetchList = async () => {
  const res = await apiDeptList(queryForm.value)
  list.value = res.data || []
}

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 部门表单
const initDeptForm = ref<Record<string, any>>({
  sort: 0,
  status: 1,
})
const deptForm = ref<Record<string, any>>({ ...initDeptForm.value })

// 表单验证规则
const deptRules = {
  pid: [{ required: true, message: '请选择上级部门', trigger: 'blur' }],
  name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入部门编码', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
}

// 表单引用
const formRef = ref()

// 查询
const handleQuery = () => {
  fetchList()
}

// 新增
const handleAdd = (pid: number) => {
  dialogTitle.value = '新增部门'
  isEdit.value = false
  // 重置表单
  Object.assign((deptForm.value = { pid: pid }), initDeptForm.value)
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑部门'
  isEdit.value = true
  // 填充表单数据
  Object.assign(deptForm.value, row)
  dialogVisible.value = true
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除【${row.name}】吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const res = await apiDeptDelete({ id: row.id })
    if (res.code == 200) {
      ElMessage.success('删除成功')
      // 从树形结构中删除部门
      doTreeData(list.value, row.id, 'delete', null)
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  })
}

// 提交表单
const submitForm = () => {
  formRef.value?.validate(async (valid: any) => {
    if (valid) {
      let res: any
      if (isEdit.value) {
        res = await apiDeptUpdate(deptForm.value)
      } else {
        res = await apiDeptAdd(deptForm.value)
      }
      if (res.code == 200) {
        ElMessage.success('保存成功')
        dialogVisible.value = false
        if (isEdit.value) {
          // 更新树形结构
          doTreeData(list.value, deptForm.value.id, 'update', res.data)
        } else {
          // 新增树形结构
          doTreeData(list.value, deptForm.value.pid, 'add', res.data)
        }
      } else {
        ElMessage.error(res.message || '保存失败')
      }
    }
  })
}

// 树形数据操作
const doTreeData = (nodes: any[], id: number, type: string, newData: any) => {
  for (const [index, node] of nodes.entries()) {
    if (node.id == id) {
      if (type === 'delete') {
        nodes.splice(index, 1)
      } else if (type === 'update') {
        nodes[index] = { ...nodes[index], ...newData }
      } else if (type === 'add') {
        nodes[index].children = nodes[index].children || []
        nodes[index].children.push(newData)
      }
    }
    if (node.children && node.children.length) {
      doTreeData(node.children, id, type, newData)
    }
  }
}

// 过滤树形数据
const filterTree = (node: any, condition: (node: any) => boolean) => {
  if (condition(node)) {
    return node
  }
  if (node.children) {
    const filteredChildren = node.children
      .map((child: any) => filterTree(child, condition))
      .filter((child: null) => child !== null)

    if (filteredChildren.length > 0) {
      return { ...node, children: filteredChildren }
    }
  }
  return null
}

// 初始化
onMounted(async () => {
  // 获取模块信息
  if (route.query?.mid) {
    const res = await apiGetModuleInfo(route.query?.mid as string)
    if (res.code === 200) {
      moduleInfo.value = res.data || {}
    }
  }
  console.log(moduleInfo.value)
  await fetchList()
})
</script>

<style scoped>
.app-container {
  padding: 0px;
}

.query-form {
  margin-bottom: 0px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  text-align: right;
}
</style>
